﻿using System;
using System.Web;
using System.Web.Script.Serialization;
using DotNetBurner.Core;
using DotNetBurner.Model;
using DotNetBurner.Web;

namespace DotNetBurner
{
    //TODO: Move this to StoryController when ASP.NET MVC supports async requests
    public class GetSubmitData : IHttpAsyncHandler
    {
        private HttpContext _context;

        public void ProcessRequest(HttpContext context)
        {
            throw new NotImplementedException();
        }

        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            _context = context;

            string url = context.Request["url"]; //.UrlDecode();

            return WebUtility.BeginGetDataFromUrl(cb, null, url);
        }

        public void EndProcessRequest(IAsyncResult result)
        {
            string content = WebUtility.EndGetDataFromUrl(result);

            var viewData = new StorySubmitData();

            if (!String.IsNullOrEmpty(content))
            {
                CachedRepository repository = new CachedRepository(SwissKnife.ConnectionString);

                HtmlUtil u = new HtmlUtil(content);
                //get story title and content
                string summary = u.GetSummary(512, 1024).DeEntitize();
                string title = u.GetTitle();

                //search for tags on content
                var topTags = repository.GetTags(50);
                string metaKeywords = u.GetKeyWords();

                //try to get the tags from title, if none was found, try content
                string tags = StoryDataHelper.GetTags(title, topTags, metaKeywords);

                if (string.IsNullOrEmpty(tags))
                    tags = StoryDataHelper.GetTags(summary, topTags, metaKeywords);

                //try to get the category
                int category = StoryDataHelper.GetCategory(title, repository);

                if (category == -1)
                    category = StoryDataHelper.GetCategory(summary, repository);

                viewData.StoryDescription = summary;
                viewData.StoryTitle = title;
                viewData.StoryTags = tags;
                viewData.StoryCategoryId = category;
            }

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            _context.Response.ContentType = "application/json";
            _context.Response.Write(serializer.Serialize(viewData));
            _context.Response.Cache.SetCacheability(HttpCacheability.Public);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}